package session.stateless.beans;

import java.io.Serializable;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.LocalBinding;

import session.stateless.SystemManager;


import entity.beans.User;
import exception.GenericException;

@Stateless
@LocalBinding(jndiBinding="SystemManagerLocal")
public class SystemManagerBean implements Serializable, SystemManager {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName="managerStore")
	private EntityManager manager;

	/* (non-Javadoc)
	 * @see session.stateless.SystemManager#regUser(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void regUser(String username, String password, String name, String lastname, String address, String cap, String city, String prov, String tel) throws GenericException {
		User u = manager.find(User.class, username.toLowerCase());
		if(u!=null) {
			// username esistente
			throw new GenericException(username);
		} else {
			u = new User(username, password, name, lastname, address, cap, city, prov, new Date());
			if(tel!="")
				u.setTel(tel);
			manager.persist(u);
		}
	}
	
	/* (non-Javadoc)
	 * @see session.stateless.SystemManager#findUser(java.lang.String)
	 */
	public User findUser(String username) throws GenericException{
		User results=null;
		Query q = manager.createNamedQuery("findUser");
		q.setParameter(1, username);
		try {
			results = (User)q.getSingleResult();
		} catch(NoResultException e) {
			throw new GenericException(username);
		}
		return results;
	}
	
	/* (non-Javadoc)
	 * @see session.stateless.SystemManager#findUser(java.lang.String)
	 */
	public long authUser(String username, String password) throws GenericException{
		long results=0;
		Query q = manager.createNamedQuery("authUser");
		q.setParameter(1, username);
		q.setParameter(2, password);
		try {
			results = (Long) q.getSingleResult();
		} catch(NoResultException e) {
			throw new GenericException(username);
		}
		return results;
	}
}
